﻿/*
Copyright (c) 2008, Thomas Ardal
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

* Neither the name of Thomas Ardal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.ComponentModel;
using System.Windows.Forms;
using Google.GData.Client;
using System.Text.RegularExpressions;

namespace Ardal.TRexGoogleContacts
{
    public partial class SettingsForm : Form
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public static bool IsShown;

        public SettingsForm()
        {
            InitializeComponent();
            var username = CredentialsHelper.GetEmail();
            var password = CredentialsHelper.GetPassword();
            if (!string.IsNullOrEmpty(username))
            {
                emailTextBox.Text = username;
            }
            if (!string.IsNullOrEmpty(password))
            {
                passwordTextBox.Text = password;
                rememberMeCheckBox.Checked = true;
            }
        }

        private void okButton_Click(object sender, EventArgs e)
        {
            if (rememberMeCheckBox.Checked)
            {
                DialogResult result = MessageBox.Show("Choosing 'Remember me on this computer' will store the inputted password on the local computer.\n" +
                                                      "This will potentially make your password available for hackers and other annoying people.\n" +
                                                      "We strongly recomment you to input the password, each time TapiRex starts up.\n\n" +
                                                      "Even though we told you not to, are your sure, that you want to store your password?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
                if (result == DialogResult.No)
                {
                    rememberMeCheckBox.Checked = false;
                    return;
                }
            }
            EnableDisableView(false);
            validateAccountWorker.RunWorkerAsync(new Credentials { Username = emailTextBox.Text, Password = passwordTextBox.Text });
        }

        private void EnableDisableView(bool enable)
        {
            label1.Enabled = enable;
            label2.Enabled = enable;
            emailTextBox.Enabled = enable;
            passwordTextBox.Enabled = enable;
            rememberMeCheckBox.Enabled = enable;
            cancelButton.Enabled = enable;
            okButton.Enabled = enable;
            pictureBox1.Visible = !enable;
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void validateAccountWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var credentials = e.Argument as Credentials;
            var result = new ValidateAccountResult { Result = ValidateAccountResultEnum.Success };
            e.Result = result;
            if (credentials != null)
            {
                try
                {
                    GoogleContactsService.SignIn(credentials);
                }
                catch (InvalidCredentialsException)
                {
                    result.Result = ValidateAccountResultEnum.InvalidCredentials;
                }
                catch (AuthenticationException)
                {
                    result.Result = ValidateAccountResultEnum.InvalidCredentials;
                }
                catch (ApplicationException exception)
                {
                    result.Result = ValidateAccountResultEnum.Error;
                    result.Exception = exception;
                }
            }
        }

        private void validateAccountWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            var result = e.Result as ValidateAccountResult;
            if (result == null) return;
            switch (result.Result)
            {
                case ValidateAccountResultEnum.Success:
                    CredentialsHelper.SetEmail(emailTextBox.Text);
                    if (rememberMeCheckBox.Checked)
                    {
                        CredentialsHelper.SetPassword(passwordTextBox.Text);
                    }
                    else
                    {
                        //Make sure that previous password is not saved
                        CredentialsHelper.ClearPassword();
                    }
                    Username = emailTextBox.Text;
                    Password = passwordTextBox.Text;
                    Close();
                    break;
                case ValidateAccountResultEnum.InvalidCredentials:
                    MessageBox.Show("Invalid credentials. Check the inputted email and password for errors.", "Invalid credentials", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    EnableDisableView(true);
                    break;
                case ValidateAccountResultEnum.Error:
                    //TODO: Log this error to TapiRex log or elsewhere.
                    MessageBox.Show(string.Format("Unknown error occured during connection with Google Contacts:\n{0}", result.Exception.Message), "Error");
                    EnableDisableView(true);
                    break;
            }
        }

        private void SettingsForm_Load(object sender, EventArgs e)
        {
            IsShown = true;
        }

        private void SettingsForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            IsShown = false;
        }
    }
}
